/*
ListController.m - Copyright (c) 1992 NeXT Computer, Inc.

You may freely copy, distribute and reuse the code in this example.
NeXT Computer, Inc. disclaims any warranty of any kind, expressed or implied, 
as to its fitness for any particular use.
*/

#import "ListController.h"
#import "MainDelegate.h"
#import "DailyBread.h"

#import <appkit/appkit.h>
#import <dbkit/dbkit.h>
#import <indexing/indexing.h>

#define NUMOFITEMS 7

@implementation ListController

- initForDateString:(const char *)theDate andRecordManager:theRM
{
    id			cursor;
    char		path[MAXPATHLEN + 1];
    
    if ([[NXBundle mainBundle] getPath:path forResource:"ListForDay" ofType:"nib"])
	[NXApp loadNibFile:path owner:self];
    
    _theDate = (char *)malloc(strlen(theDate)+2);
    strcat(strcpy(_theDate, theDate), " ");
    _records = theRM;
    cursor = [_records cursorForAttributeNamed:"TheDate"];
    if ([cursor setKey:(void *)_theDate andLength:(strlen(_theDate) + 1)] == YES) {
	_theHandle = [cursor setFirstHandle];
	dailyBread = [_records readRecord:_theHandle fromZone:[self zone]];
    } else {
	dailyBread = [[DailyBread alloc] initForDate:_theDate];
	_theHandle = [_records addRecord:dailyBread];
    }

    [window setTitle:_theDate];
    [tableView setDataSource:self];
    [commentVector setIdentifier:dailyBread];
    doneObj = [[Object alloc] init];
    [doneVector setIdentifier:doneObj];
    [tableView display];
    [window makeKeyAndOrderFront:self];
    return self;
}

- finishItem:sender
{
    return self;
}

- free
{
    [dailyBread free];
    return [super free];
}

- (char *)theDate
{
    return _theDate;
}

- windowWillClose:sender
{
    [self saveTheRecord:sender];
    [[NXApp delegate] windowWillDisappear:self];
    return self;
}

- orderUp:sender
{
    [[tableView window] makeKeyAndOrderFront:sender];
    return self;
}

- saveTheRecord:sender
{
    id                  storeFile;
    unsigned            handle;

    [_records getBlock:&handle andStore:&storeFile];

    // this is *VERY* important to be sure the changes make it into the store. 
    [_records replaceRecord:_theHandle with:dailyBread];
    [storeFile commitTransaction];

    return self;
}

// these are the DataSource methods needed by the tableView.

- (unsigned int)rowCount
{
    return 7;
}

- getValueFor:identifier at:(unsigned int)aPosition into:aValue
{
    if (identifier == dailyBread)
	[aValue setStringValue:[dailyBread number:(int)aPosition]];

    if (identifier == doneObj)
	[aValue setStringValue:[dailyBread done:(int)aPosition] ? "Y" : ""];

    return self;
}

- setValueFor:identifier at:(unsigned int)aPosition from:aValue
{
    if (identifier == dailyBread)
	[dailyBread setNumber:(int)aPosition to:[aValue stringValue]];

    if (identifier == doneObj)
	[dailyBread setDone:(int)aPosition to:strcmp([aValue stringValue], "")];

    return self;
}

- pullUndoneForward:sender
{
    return self;
}

@end
